package models;

import play.*;
import play.data.binding.As;
import play.data.validation.Required;
import play.db.jpa.*;
import play.modules.search.Field;
import play.modules.search.Indexed;

import javax.persistence.*;

import java.util.*;

@Indexed
@Entity
public class Answer extends Model {
	
	@As("yyyy-MM-dd")
	public Date postedAt;
	
	@Field
	@Required
	public String content;
	
	@ManyToOne
	@Field
	public User postedBy;
	
	@Field
	@Required
	public String title;
	
	@ManyToMany(cascade=CascadeType.PERSIST)
	public Set<User> voters;
	
	@OneToMany(mappedBy="answer", cascade=CascadeType.ALL)
    public Set<Vote> votes;
	
	@ManyToOne
	public Question question;
	
	public Answer(Question question, User postedBy, String title, String content) {
		this.question = question;
		this.postedBy = postedBy;
		this.title = title;
		this.content = content;
		this.postedAt = new Date();
		create();
	}
	
	public int voteCount() {
		return voters.size();
	}
	
	/**
	 * Somve vote handling
	 */
	//Get number of upvotes for a specific lecture
    public long getUpvoteCount() {
    	return Vote.count("answer = ? and positive = true", this);
    }
    
  //Get number of downvotes for a specific lecture
    public  long getDownvoteCount() {
    	return Vote.count("answer = ? and positive = false", this);
    }
}
